<script setup lang="ts">
/* eslint-disable vue/no-mutating-props */
import { ref, reactive, computed, nextTick, watch } from 'vue'
import {
  ElMessage,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElCard,
  ElRow,
  ElCol,
  ElButton,
  ElInputNumber,
  type FormInstance,
  type FormRules
} from 'element-plus'
import { getEditInfoApi, updatePriceApi } from '@/api/warehouse/merchandiseOffers'

interface Props {
  visible: boolean
  editData?: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  editData: null
})

const emit = defineEmits<Emits>()
// 移动端检测
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const isMobile = computed(() => appStore.getMobile)

// 响应式控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const loading = ref(false)
const formRefs = ref<FormInstance[]>([])

// 币种列表
const currencyLists = ref([
  { value: 214, label: '美金', disabled: false },
  { value: 4, label: '人民币', disabled: false }
])

const realArrivalDate = ref('')

// 价格列表数据 - 固定美金(214)和人民币(4)
const priceLists = ref<
  Array<{
    value: number
    label: string
    price: number | string | null
    first_leg_logistics_fee: number | string | null
    discount: Array<{
      level: number
      num?: number | null
      price?: number | null
    }>
    level: number
    remark?: string
  }>
>([
  {
    value: 214, // 固定选中美金
    label: '美金',
    price: null,
    first_leg_logistics_fee: null,
    discount: [{ level: 1, num: 100, price: null }],
    level: 1,
    remark: ''
  },
  {
    value: 4, // 固定选中人民币
    label: '人民币',
    price: null,
    first_leg_logistics_fee: null,
    discount: [{ level: 1, num: 100, price: null }],
    level: 1,
    remark: ''
  }
])

// 表单验证规则
const rules = ref<FormRules>({
  currency_id: [{ required: true, message: '请选择币种', trigger: 'change' }],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: Function) => {
        if (!value || Number(value) <= 0) {
          callback(new Error('价格必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  first_leg_logistics_fee: [
    {
      validator: (rule: any, value: any, callback: Function) => {
        // 空值或大于0都通过，只有0或负数才报错
        if (value && Number(value) <= 0) {
          callback(new Error('头程物流费必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 价格输入处理
const handlePriceInput = (current: any) => {
  // 格式化价格输入
  current.price = current.price
    .replace(/[^\d.]/g, '')
    .replace(/\.{2,}/g, '.')
    .replace('.', '$#$')
    .replace(/\./g, '')
    .replace('$#$', '.')
    .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    .replace(/^\./g, '')

  // 自动同步价格到第一个折扣价格
  if (current.price && Number(current.price) > 0) {
    if (current.discount && current.discount.length > 0) {
      current.discount[0].price = Number(current.price)
    }
  } else {
    // 如果价格为空，也清空第一个折扣价格
    if (current.discount && current.discount.length > 0) {
      current.discount[0].price = null
    }
  }
}

// 新增折扣梯度
const handleGradientAdd = (currencyValue: number) => {
  const targetIndex = priceLists.value.findIndex((item) => item.value === currencyValue)
  if (targetIndex === -1) return

  const currentRow = priceLists.value[targetIndex]
  if (currentRow.discount.length >= 5) {
    ElMessage.error({ message: '最多只能添加5个折扣梯度', center: true })
    return
  }

  currentRow.discount.push({
    level: currentRow.discount.length + 1,
    num: undefined,
    price: undefined
  })
}

// 删除折扣梯度
const handleGradientDelete = (currencyValue: number) => {
  const targetIndex = priceLists.value.findIndex((item) => item.value === currencyValue)
  if (targetIndex === -1) return

  const currentRow = priceLists.value[targetIndex]
  if (currentRow.discount.length <= 1) {
    ElMessage.error({ message: '至少保留一个折扣梯度', center: true })
    return
  }

  // 删除最后一个折扣梯度
  currentRow.discount.pop()

  // 重新编号所有折扣梯度，确保level从1开始连续
  currentRow.discount.forEach((discount, index) => {
    discount.level = index + 1
  })
}

// 动态表单校验
const ruleFn = (key: string, discountList: any[], currentGradientIndex: number) => {
  const rules = {
    num: () => ({
      required: true,
      trigger: ['blur', 'change'],
      validator: (_: any, value: string, callback: Function) => {
        if (!value) {
          callback(new Error('请输入数量'))
        } else if (
          currentGradientIndex &&
          parseFloat(value) <= discountList[currentGradientIndex - 1].num
        ) {
          callback(
            new Error(`数量${discountList[currentGradientIndex].level}不能小于或等于上一级数量`)
          )
        } else {
          callback()
        }
      }
    }),
    price: () => ({
      required: true,
      trigger: ['blur', 'change'],
      validator: (_: any, value: string, callback: Function) => {
        if (!value) {
          callback(new Error('请输入折扣价格'))
        } else {
          callback()
        }
      }
    })
  }
  return rules[key]()
}

// 获取编辑信息
const getEditInfo = async () => {
  if (!props.editData) return

  try {
    const res = await getEditInfoApi(props.editData.id, {
      wid: props.editData.wid || '',
      fl_warehouse_id: props.editData.fl_warehouse_id || '',
      is_futures: props.editData.is_futures || 0,
      arrival_date: props.editData.arrival_date || ''
    })

    // 重置所有价格数据
    priceLists.value.forEach((priceItem) => {
      priceItem.price = null
      priceItem.discount = [{ level: 1, num: 100, price: null }]
    })

    // 如果API返回数据，更新对应币种的价格信息
    if (res.data.prices && res.data.prices.length > 0) {
      res.data.prices.forEach((item: any) => {
        // 根据 currency_id 或 transaction_currency_id 查找对应币种
        const currencyId = item.currency_id || item.transaction_currency_id
        const priceItem = priceLists.value.find(
          (priceListItem) => priceListItem.value === currencyId
        )

        if (priceItem) {
          // 处理价格：如果是空字符串或无效值，保持为null
          const apiPrice = item.price || item.transaction_price
          priceItem.price = apiPrice && apiPrice !== '' ? Number(apiPrice) : null
          priceItem.first_leg_logistics_fee = item.first_leg_logistics_fee || null
          priceItem.remark = item.remark

          // 处理 discount 数据结构
          if (item.discount && Array.isArray(item.discount)) {
            // 如果是数组格式：[{level: 1, num: "100", price: "2300.00"}, ...]
            priceItem.discount = item.discount.map((discountItem: any) => ({
              level: Math.max(1, Number(discountItem.level) || 1),
              num: Number(discountItem.num || 0),
              price: Number(discountItem.price || 0)
            }))
          } else if (item.discount && typeof item.discount === 'object') {
            // 如果是对象格式：{"1": {"num": "100", "price": "600.00"}, ...}
            priceItem.discount = Object.keys(item.discount)
              .map((level, index) => ({
                level: Math.max(1, Number(level) || index + 1),
                num: Number(item.discount[level].num || 0),
                price: Number(item.discount[level].price || 0)
              }))
              .sort((a, b) => a.level - b.level)
          } else {
            priceItem.discount = [{ level: 1, num: 100, price: null }]
          }
        }
      })
    }

    if (res.data.real_arrival_date && res.data.real_arrival_date.length == 1) {
      //
      realArrivalDate.value = res.data.real_arrival_date[0]
    }
  } catch (error) {
    console.error('获取编辑信息失败:', error)
  }
}

// 数据验证
const validateData = () => {
  // 美金价格必填验证
  const usdItem = priceLists.value.find((item) => item.value === 214)
  if (!usdItem || !usdItem.price || Number(usdItem.price) <= 0) {
    ElMessage.error({ message: '美金价格必填', center: true })
    return false
  }

  // 验证填写了价格的币种的折扣信息
  for (const item of priceLists.value) {
    if (item.price && Number(item.price) > 0) {
      for (let i = 0; i < item.discount.length; i++) {
        const discount = item.discount[i]
        if (!discount.num || Number(discount.num) <= 0) {
          ElMessage.error({ message: `请输入${item.label}的折扣数量${i + 1}`, center: true })
          return false
        }
        if (!discount.price || Number(discount.price) <= 0) {
          ElMessage.error({ message: `请输入${item.label}的折扣价格${i + 1}`, center: true })
          return false
        }
      }
    }
  }

  // 验证美元和人民币相同level的num必须相等
  const usdPriceItem = priceLists.value.find((item) => item.value === 214)
  const cnyPriceItem = priceLists.value.find((item) => item.value === 4)

  // 只有当两个币种都有价格时才进行验证
  if (
    usdPriceItem &&
    usdPriceItem.price &&
    Number(usdPriceItem.price) > 0 &&
    cnyPriceItem &&
    cnyPriceItem.price &&
    Number(cnyPriceItem.price) > 0
  ) {
    // 获取两个币种的折扣数据
    const usdDiscounts = usdPriceItem.discount || []
    const cnyDiscounts = cnyPriceItem.discount || []

    // 创建level到num的映射
    const usdLevelNumMap = new Map()
    const cnyLevelNumMap = new Map()

    usdDiscounts.forEach((discount) => {
      if (discount.level && discount.num) {
        usdLevelNumMap.set(discount.level, Number(discount.num))
      }
    })

    cnyDiscounts.forEach((discount) => {
      if (discount.level && discount.num) {
        cnyLevelNumMap.set(discount.level, Number(discount.num))
      }
    })

    // 检查相同level的num是否相等
    for (const [level, usdNum] of usdLevelNumMap) {
      if (cnyLevelNumMap.has(level)) {
        const cnyNum = cnyLevelNumMap.get(level)
        if (usdNum !== cnyNum) {
          ElMessage.error({
            message: `美元和人民币的折扣级别${level}的数量必须相等（美元：${usdNum}，人民币：${cnyNum}）`,
            center: true
          })
          return false
        }
      }
    }

    // 反向检查，确保人民币有的level美元也有相同的num
    for (const [level, cnyNum] of cnyLevelNumMap) {
      if (usdLevelNumMap.has(level)) {
        const usdNum = usdLevelNumMap.get(level)
        if (usdNum !== cnyNum) {
          ElMessage.error({
            message: `美元和人民币的折扣级别${level}的数量必须相等（美元：${usdNum}，人民币：${cnyNum}）`,
            center: true
          })
          return false
        }
      }
    }
  }

  return true
}

// 保存数据
const handleSave = async () => {
  try {
    // 手动验证数据
    if (!validateData()) {
      return
    }

    // 过滤出有效的价格数据（价格不为空且大于0）
    const validPrices = priceLists.value.filter((item) => {
      return item.price && Number(item.price) > 0
    })

    const params = {
      wid: parseInt(props.editData.wid),
      fl_warehouse_id: parseInt(props.editData.fl_warehouse_id),
      is_futures: props.editData.is_futures,
      arrival_date: props.editData.arrival_date,
      productid: props.editData.id,
      prices: validPrices,
      real_arrival_date: realArrivalDate.value
    }

    const res = await updatePriceApi(params)

    if (res) {
      ElMessage.success({ message: '保存成功', center: true })
      emit('success')
      dialogVisible.value = false
    }
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  realArrivalDate.value = ''
}

// 聚焦到美金价格输入框
const focusUsdInput = () => {
  setTimeout(() => {
    try {
      // 方法1：通过第一个卡片查找美金价格输入框
      const firstCard = document.querySelector('.el-card')
      if (firstCard) {
        const priceInput = firstCard.querySelector('.el-input input') as HTMLInputElement
        if (priceInput && priceInput.placeholder === '请输入价格') {
          priceInput.focus()
          priceInput.select()
          return
        }
      }

      // 方法2：通过placeholder属性直接查找
      const priceInput = document.querySelector(
        'input[placeholder="请输入价格"]'
      ) as HTMLInputElement
      if (priceInput) {
        priceInput.focus()
        priceInput.select()
        return
      }

      // 方法3：遍历所有文本输入框查找
      const textInputs = document.querySelectorAll('input[type="text"]')
      for (let i = 0; i < textInputs.length; i++) {
        const htmlInput = textInputs[i] as HTMLInputElement
        if (htmlInput.placeholder === '请输入价格') {
          htmlInput.focus()
          htmlInput.select()
          return
        }
      }
    } catch (error) {
      console.error('自动聚焦失败:', error)
    }
  }, 1000)
}

// 监听弹窗打开
watch(
  () => props.visible,
  (newVal) => {
    if (newVal && props.editData) {
      nextTick(() => {
        getEditInfo()
      })
    }
  }
)
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑商品报价"
    width="1400px"
    :close-on-click-modal="false"
    @close="handleClose"
    @opened="focusUsdInput"
    class="mobile-dialog"
  >
    <!-- 基础信息 -->
    <el-descriptions title="基础信息" :column="2" border class="mb-4">
      <el-descriptions-item label="仓库">
        {{ editData?.warehouseName }}
      </el-descriptions-item>
      <el-descriptions-item label="商品名称">
        {{ editData?.cname }}
      </el-descriptions-item>
      <el-descriptions-item label="算力">
        {{ editData?.hashrate }}
      </el-descriptions-item>
      <el-descriptions-item label="库存类型">
        {{ editData?.is_futures_text }}
      </el-descriptions-item>
      <el-descriptions-item label="到货日期">
        {{ editData?.arrival_date }}
      </el-descriptions-item>
      <el-descriptions-item label="真实到货日期">
        <el-date-picker
          v-if="editData?.is_futures > 0"
          v-model="realArrivalDate"
          type="date"
          placeholder="选择真实到货日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
        <span v-else>{{ realArrivalDate }}</span>
      </el-descriptions-item>
      <el-descriptions-item label="库存汇总">
        {{ editData?.quantity }}
      </el-descriptions-item>
    </el-descriptions>

    <!-- 价格配置 -->
    <div v-for="currencyItem in priceLists" :key="`${currencyItem.value}-${currencyItem.level}`">
      <el-card shadow="never" class="mb-4">
        <el-form :model="currencyItem" :rules="rules" label-width="100px">
          <el-form-item label="币种" prop="value">
            <el-select
              v-model="currencyItem.value"
              placeholder="请选择币种"
              :clearable="false"
              :disabled="true"
              style="width: 100%"
            >
              <el-option
                v-for="item in currencyLists"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="头程物流费" prop="first_leg_logistics_fee">
            <el-input
              v-model="currencyItem.first_leg_logistics_fee"
              placeholder="请输入头程物流费"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="价格" prop="price">
            <el-input
              v-model="currencyItem.price"
              placeholder="请输入价格"
              @input="handlePriceInput(currencyItem)"
              style="width: 100%"
            />
          </el-form-item>

          <!-- 折扣梯度 -->
          <div v-if="currencyItem.discount && currencyItem.discount.length">
            <div
              v-for="(currentGradient, index) in currencyItem.discount"
              :key="currentGradient.level"
            >
              <el-row :gutter="24" align="middle">
                <el-col :span="isMobile ? 24 : 8">
                  <el-form-item :label="`数量 ${index + 1}`">
                    <el-input-number
                      :model-value="currentGradient.num === null ? undefined : currentGradient.num"
                      @update:model-value="currentGradient.num = $event"
                      :min="1"
                      :precision="0"
                      placeholder="请输入数量"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="isMobile ? 24 : 8">
                  <el-form-item :label="`折扣价格 ${index + 1}`">
                    <el-input-number
                      :model-value="
                        currentGradient.price === null ? undefined : currentGradient.price
                      "
                      @update:model-value="currentGradient.price = $event"
                      :precision="2"
                      placeholder="请输入折扣价格"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="isMobile ? 24 : 8" v-if="index === 0">
                  <el-form-item label="">
                    <el-button @click="handleGradientAdd(currencyItem.value)">新增</el-button>
                    <el-button
                      v-if="currencyItem.discount.length > 1"
                      @click="handleGradientDelete(currencyItem.value)"
                    >
                      删除
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>

          <el-form-item label="备注">
            <el-input v-model="currencyItem.remark" placeholder="请输入备注" type="textarea" />
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer flex justify-end">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSave"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
